package br.com.informatos.controle;

import java.util.List;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import br.com.informatos.modelo.entidades.Time;
import br.com.informatos.repositorio.TimeRepositorio;

@ManagedBean
public class TimeBean {

	private Time time = new Time();
	private List<Time> times;

	public void adiciona() {
		EntityManager manager = this.getManager();
		TimeRepositorio repositorio = new TimeRepositorio(manager);
		if (this.time.getId() == null) {
			repositorio.adiciona(this.time);
		}else {
			repositorio.atualiza(this.time);
		}
		this.time = new Time();
		this.time = null;

	}

	public void preparaAlteracao() {
		Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		Long id = Long.parseLong(params.get("id"));
		EntityManager manager = this.getManager();
		TimeRepositorio repositorio = new TimeRepositorio(manager);
		this.time = repositorio.procura(id);
	}

	public void remove () {
		Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		Long id = Long.parseLong(params.get("id"));
		EntityManager manager = this.getManager();
		TimeRepositorio repositorio = new TimeRepositorio(manager);
		repositorio.remove(id);
		this.times = null;
	}

	public List<Time> getTimes() {
		if (this.times == null) {
			EntityManager manager = this.getManager();
			TimeRepositorio repositorio = new TimeRepositorio(manager);
			this.times = repositorio.getLista();
		}
		return this.times;
	}

	private EntityManager getManager() {
		FacesContext fc = FacesContext.getCurrentInstance();
		ExternalContext ec = fc.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ec.getRequest();
		return (EntityManager) request.getAttribute("EntityManager");
	}



	//getters e setters
	public Time getTime() {
		return time;
	}

	public void setTime(Time time) {
		this.time = time;
	}

	public void setTimes(List<Time> times) {
		this.times = times;
	}









}
